<template>
  <a-modal :title="title" :width="700" :visible="visible" :confirmLoading="confirmLoading" @ok="handleOk" @cancel="handleCancel" cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="coverImage" label="封面图">
          <JImageUpload :uploadParams="getUploadParams()" :isMultiple="true" :fileSize="2" :number="1" :accept="'image/*'" @fileChange="homeImageChange" v-model="model.coverImage"></JImageUpload>
          <div class="upload__tip" style="line-height: 16px;">建议尺寸345*140px，上传2M以内jpg、png格式图片</div>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :colon="false" prop="name" required label="活动名称:">
          <a-input placeholder="" v-model="model.name" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brandId" required label="品牌">
          <a-select ref="select" v-model="model.brandId">
            <a-select-option :value="item.id" v-for="(item, index) in brandOption" :key="index">{{ item.brandName }} </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :colon="false" prop="address" required label="活动地址:">
          <a-input placeholder="" v-model="model.address" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :colon="false" prop="longitude" required label="经度:">
          <a-input placeholder="" v-model="model.longitude" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :colon="false" prop="latitude" required label="纬度:">
          <a-input placeholder="" v-model="model.latitude" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :colon="false" prop="price" required label="积分价格:">
          <a-input-number placeholder="请输入正整数" v-model="model.price" :min="0" :precision="0" style="width: 436px;" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="divAdd" label="活动排期:">
          <a-button @click="divAdd" type="primary" icon="plus">添加</a-button>
        </a-form-model-item>
        <!-- <div style="height: 330px;overflow: scroll;"> -->
        <div style="margin-left:80px;margin-top: -20px;">
          <div v-for="(row, index) in model.scheduleVoList" :key="index" style="position: relative;">
            <div style="padding: 20px 10px;border-bottom: 1px solid #ccc;">
              <a-form-model-item label="选择日期:" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="'scheduleVoList.' + index + '.dates'" :rules="validatorRules.dates">
                <!-- 日期多选 -->
                <div class="bg-white p-2 w-full border rounded" style="border: 1px solid #ccc;word-wrap: break-word;width: 368px;padding: 3px 5px; border-radius: 4px;">
                  <date-picker v-model="selecteddate" :min-date="new Date()">
                    <template #default="{ inputValue, togglePopover, hidePopover }">
                      <div style="display: flex; justify-content: space-between;">
                        <div class="" style="display:flex;flex-wrap: wrap; width: 300px;">
                          <div
                            v-for="(date, i) in row.dates"
                            :key="i"
                            class="items-center bg-indigo-100 hover:bg-indigo-200 text-sm text-indigo-600 font-semibold h-8 px-2 m-1 rounded-lg border-2 border-transparent focus:border-indigo-600 focus:outline-none"
                            @click.stop="dateSelected($event, date, togglePopover, index)"
                            ref="button"
                            style="display:flex; width: 100px; height: 25px; line-height: 25px;"
                          >
                            {{ JSON.parse(JSON.stringify(date)).date }}
                            <a-icon type="close-circle" style="height: 28px;line-height: 28px;font-size: 12px;margin-left: 5px;" @click.stop="removeDate(date, hidePopover, index)" />
                          </div>
                        </div>
                        <a-icon type="schedule" @click.stop="addDate(index)" style="height: 26px;line-height: 33px;font-size:20px;" />
                      </div>
                    </template>
                  </date-picker>
                </div>
              </a-form-model-item>
              <div v-for="(row1, index1) in model.scheduleVoList[index].sessionsDtoList" :key="index1" class="divList">
                <a-form-model-item label="场次时间" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="'scheduleVoList.' + index + '.sessionsDtoList.' + index1 + '.h'" :rules="validatorRules.h">
                  <!-- <div class="time_box" @click="timeshow=true"  v-show="!timeshow">请选择</div> -->
                  <div ref="timePicker" class="timePicker">
                    <a-select v-model="row1.h" placeholder="时" :showArrow="false" style="width: 50px;height: 32px;">
                      <a-select-option :value="item.h" v-for="item in optionsH" :key="item.m"> {{ item.h }} </a-select-option>
                    </a-select>
                    <span>:</span>
                    <a-select v-model="row1.m" placeholder="分" style="width: 50px" :showArrow="false">
                      <a-select-option :value="item.m" v-for="item in optionsM" :key="item.m"> {{ item.m }} </a-select-option>
                    </a-select>
                    <span>-</span>
                    <a-select v-model="row1.h1" placeholder="时" :showArrow="false" style="width: 50px">
                      <a-select-option :value="item.h" v-for="item in optionsH" :key="item.h"> {{ item.h }} </a-select-option>
                    </a-select>
                    <span>:</span>
                    <a-select v-model="row1.m1" placeholder="分" style="width: 50px" :showArrow="false">
                      <a-select-option :value="item.m" v-for="item in optionsM" :key="item.m"> {{ item.m }} </a-select-option>
                    </a-select>
                  </div>
                </a-form-model-item>
                <a-form-model-item
                  label="预约名额上限"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  :prop="'scheduleVoList.' + index + '.sessionsDtoList.' + index1 + '.maxNum'"
                  :rules="validatorRules.maxNum"
                >
                  <a-input-Number v-model="row1.maxNum" type="Number" :min="0" :precision="0" style="width: 368px;" />
                </a-form-model-item>
                <img src="../../../../assets/invite/bairuidelete.png" class="bairuidelete" @click="deleteDivList(index, index1)" v-show="index1 !== 0" />
              </div>
              <div @click="addchangci(index)" class="addChangci">
                <a-icon type="plus-circle" :style="{ fontSize: '24px' }" />
                <div class="addtext">添加场次</div>
              </div>
            </div>
            <div
              style="    
                font-size: 20px;
                position: absolute;
                top: 6px;
                right: 20px;
                cursor: pointer;"
              @click="deleteDateDiv(index)"
              v-show="index !== 0"
            >
              <a-icon type="close-circle" />
            </div>
          </div>
        </div>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status" label="状态">
          <!-- <a-input v-model="model.description"/> -->
          <a-radio-group v-model="model.status" name="radioGroup">
            <a-radio :value="0">启用</a-radio>
            <a-radio :value="1">禁用</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="details" label="活动介绍">
          <JImageUpload
            :uploadParams="getUploadParams()" 
            :isMultiple="true" 
            :fileSize="2" :number="9" 
            :accept="'image/*'" 
            @fileChange="homeImageChange1" 
            v-model="model.details"
          ></JImageUpload>
          <div class="upload__tip" style="line-height: 16px;">建议尺寸345*140px，上传2M以内jpg、png格式图片</div>
        </a-form-model-item>
        <!-- <a-form-model-item label="活动介绍" style="min-height: 300px" prop="details" :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <j-editor v-model="model.details" />
        </a-form-model-item> -->
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { brandList, saveOrUpdateParameter, getActivityById } from '@/api/marketingCenter/invite.js'
import globalData from '@/assets/js/common'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import JEditor from '../JEditor.vue'
import DatePicker from 'v-calendar/lib/components/date-picker.umd'
export default {
  name: 'par',
  components: { JImageUpload, JEditor, DatePicker },
  props: {
    typeNum: {
      type: String,
      default: ''
    }
  },
  data() {
    const _this = this
    let maxNum = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please Enter StatedRate'))
      } else {
        callback()
      }
    }
    let h = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please Enter StatedRate'))
      } else if (value == 'undefined') {
        callback(new Error('Please Enter StatedRate'))
      } else {
        callback()
      }
    }
    let dates = (rule, value, callback) => {
      var arr = []
      var newString = ''
      this.textList.scheduleVoList.forEach(e => {
        newString = e.dates
        arr.push(newString)
      })
      var bbb = arr.toString().split(',')
      let newArr = new Set(bbb)
      if (value.length == 0) {
        callback(new Error('请选择日期!'))
      } else if (bbb.length !== newArr.size) {
        callback(new Error('日期不可以重复!'))
      } else {
        callback()
      }
    }
    return {
      selecteddate: '',
      selecteddate1: [],
      index: '',
      textList: [],
      optionsH: [],
      optionsM: [],
      optionsS: [],
      dates: [
        {
          date: new Date()
        }
      ],
      timeshow: false,
      h: '00',
      m: '00',
      h1: '00',
      m1: '00',
      selected: {},
      title: '操作',
      visible: false,
      model: {
        scheduleVoList: [{ dates: [{ date: '' }] }, {}],
        status: 0,
        details: '<h2 style="text-align: center;">富文本编辑器</h2> <p>这里是富文本编辑器。</p>'
      },
      labelCol: {
        xs: { span: 18 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      brandOption: [],
      validatorRules: {
        coverImage: [{ required: true, message: '请上传图片!' }],
        name: [{ required: true, message: '请输入活动名称!' }],
        address: [{ required: true, message: '请输入活动地址!' }],
        price: [{ required: true, message: '请输入积分价格!' }],
        brandId: [{ required: true, message: '请选择品牌!' }],
        status: [{ required: true, message: '请选择状态!' }],
        latitude: [{ required: true, message: '请输入!' }],
        longitude: [{ required: true, message: '请输入!' }],
        h: [{ validator: h, required: true, message: '请输入场次时间!' }],
        dates: [{ validator: dates, required: true }],
        maxNum: [{ validator: maxNum, required: true, message: '请输入预约名额上限!' }],
        details: [{ required: true, message: '请上传图片!' }]
      }
    }
  },
  watch: {
    selecteddate: {
      handler(newName) {
        let index2 = this.model.scheduleVoList[this.index].dates.length - 1
        var nowName = new Date().toLocaleDateString().replace(/(\/)/g, '-')
        newName = new Date(newName).toLocaleDateString().replace(/(\/)/g, '-')
        console.log(new Date().toLocaleDateString().replace(/(\/)/g, '-'))
        console.log(newName, '11111')
        if (newName == '1970-1-1') {
          this.model.scheduleVoList[this.index].dates[index2].date = nowName
        } else {
          this.model.scheduleVoList[this.index].dates[index2].date = newName
        }
      }
    }
  },
  created() {
    for (let i = 0; i <= 23; i++) {
      let h
      i < 10 ? (h = '0' + i) : (h = i)
      this.optionsH.push({
        h
      })
    }
    for (let i = 0; i <= 59; i++) {
      let m
      i < 10 ? (m = '0' + i) : (m = i)
      this.optionsM.push({
        m
      })
    }
    this.getbrandList()
  },
  methods: {
    addDate(index) {
      var leixing = typeof this.model.scheduleVoList[index].dates
      if (leixing == 'string') {
        var aa = []
        aa.push({
          date: new Date().toLocaleDateString().replace(/(\/)/g, '-')
        })
        this.model.scheduleVoList[index].dates = aa
      } else {
        this.model.scheduleVoList[index].dates.push({
          date: new Date().toLocaleDateString().replace(/(\/)/g, '-')
        })
      }
      this.index = index
      this.selecteddate1 = this.model.scheduleVoList[index].dates
      this.$nextTick(() => {
        const btn = this.$refs.button[this.$refs.button.length - 1]
        btn.click()
      })
    },
    removeDate(date, hide, index) {
      this.model.scheduleVoList[index].dates = this.model.scheduleVoList[index].dates.filter(d => d !== date)
      hide()
    },
    dateSelected(e, date, toggle, index) {
      // this.selected = date
      let str = JSON.parse(JSON.stringify(date)).date
      this.selecteddate = str.replace(/(\/)/g, '-')
      toggle({ ref: e.target })
    },
    //删除活动排期
    deleteDateDiv(index) {
      this.model.scheduleVoList.splice(index, 1)
    },
    //添加盒子
    divAdd() {
      this.model.scheduleVoList.push({
        dates: [],
        sessionsDtoList: [{ h: '00',
        h1: '00',
        m: '00',
        m1: '00',startTime: '', endTime: '', maxNum: '' }]
      })
    },
    // 删除盒子
    deleteDivList(e, e1) {
      this.model.scheduleVoList[e].sessionsDtoList.splice(e1, 1)
    },
    addchangci(index) {
      this.model.scheduleVoList[index].sessionsDtoList.push({
        h: '00',
        h1: '00',
        m: '00',
        m1: '00',
        startTime: '',
        endTime: '',
        maxNum: ''
      })
    },
    getbrandList() {
      brandList().then(res => {
        if (res.code == 200) {
          this.brandOption = res.data
        }
      })
    },
    add() {
      this.edit({
        status: 0,
        scheduleVoList: [
          {
            dates: [],
            sessionsDtoList: [{ h: '00', h1: '00', m: '00', m1: '00', endTime: '', maxNum: '' }]
          }
        ]
      })
    },
    edit(record) {
      if (record.id) {
        getActivityById({ id: record.id }).then(res => {
          if (res.data.scheduleVoList.length != 0) {
            res.data.scheduleVoList.forEach(e => {
              var bbb = e.dates.split(',') //转成数组
              var ccc = []
              bbb.forEach(e => {
                // e = new Date(Date.parse(e.replace(/-/g, "/")));//转成newDate格式
                ccc.push({ date: e }) //转成渲染格式
              })
              e.dates = ccc
              e.sessionsDtoList.forEach(el => {
                var dd = el.startTime.split(':')
                var cc = el.endTime.split(':')
                el.h = dd[0]
                el.m = dd[1]
                el.h1 = cc[0]
                el.m1 = cc[1]
              })
            })
          }
          this.model = Object.assign({}, res.data)
        })
        this.visiblekey = true
      } else {
        this.visiblekey = false
        this.model = Object.assign({}, record)
      }
      this.visible = true
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    homeImageChange(list) {
      this.model.coverImage = list.length > 0 ? list[0].url : []
    },
    homeImageChange1(list) {
      var aa = []
      list.forEach(e => {
        aa.push(e.url)
      })
      console.log(aa.toString())
      this.model.details = aa.toString()
      // this.model.details = list.length > 0 ? list[0].url : []
    },
    protectionImageChange(list) {
      this.model.protectionHomeImage = list.length > 0 ? list[0].url : []
    },
    benefitsImageChange(list) {
      this.model.benefitsPackageImage = list.length > 0 ? list[0].url : []
    },
    //newDate转成年月日
    dateFormat(dateData) {
      const date = new Date(dateData)
      const y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? `0${m}` : m
      let d = date.getDate()
      d = d < 10 ? `0${d}` : d
      const time = `${y}-${m}-${d}`
      return time
    },
    // 确定
    handleOk() {
      this.textList = JSON.parse(JSON.stringify(this.model))
      this.textList.scheduleVoList.forEach(e => {
        var arr = []
        e.dates.forEach(el => {
          arr.push(el.date) //时间newDate转成年月日放进数组
        })
        e.dates = arr.toString() //数组转换成字符串
        e.sessionsDtoList.forEach(el => {
          el.startTime = el.h + ':' + el.m
          el.endTime = el.h1 + ':' + el.m1
          delete el.h, delete el.h1, delete el.m, delete el.m1
        })
      })
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let obj
          if (!this.textList.id) {
            obj = saveOrUpdateParameter(this.textList)
          } else {
            obj = saveOrUpdateParameter(this.textList)
          }
          obj
            .then(res => {
              if (res.success) {
                that.$message.success(res.msg)
                that.$emit('ok')
                that.confirmLoading = false
                that.close()
              } else if (res.code == 500) {
                that.$message.warning(res.msg)
                that.confirmLoading = false
              } else {
                that.$message.warning(res.msg)
              }
            })
            .finally(() => {
              console.log('1111111')
              // that.confirmLoading = false
              // that.close()
            })
        } else {
          return false
        }
      })
    },
    // 关闭
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.fileList = []
      this.timeshow = false
      this.h = ''
      this.h1 = ''
      this.m = ''
      this.m1 = ''
      this.visible = false
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style scoped lang="less">
.addChangci {
  margin-left: 160px;
  display: flex;
}

.addtext {
  margin: 2px 0px 5px 10px;
}

.divList {
  position: relative;
}

.bairuidelete {
  position: absolute;
  top: 50px;
  right: 0px;
  width: 30px;
  height: 30px;
}

.timePicker {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;

  /deep/.ant-select {
    .ant-select-selection {
      border: none !important;
    }

    .ant-select-selection__rendered {
      height: 100%;
    }

    .ant-select-selector {
      border: none !important;
    }

    .ant-select-selection {
      border: none !important;
      box-shadow: none;
    }
  }
}

.time_box {
  width: 368px;
  height: 32px;
  line-height: 32px;
  border: 1px solid #d9d9d9;
  color: #bfbfbf;
  padding-left: 11px;
  border-radius: 4px;
}

/deep/.ant-form-item-control {
  line-height: 32px !important;
}
</style>
